import 'dart:async';

import 'dart:io';
import 'package:mahjong/util/CustomerDialog.dart';

class MessageUtils {
  // 长连接对象
  static WebSocket webSocket;

  // 是否已经连接
  static bool isconnect = false;

  static Timer heartTimer;

  static void connect(Function callBack, String url) {
    if (webSocket != null) {
      return;
    }
    CustomerDialog.loading("连接服务器中...");
    Future<WebSocket> futureWebSocket =
        WebSocket.connect(url); // Api.WS_URL 为服务器端的 websocket 服务
    futureWebSocket.then((WebSocket ws) {
      CustomerDialog.closeAllLoading();
      webSocket = ws;
      isconnect = true;
      heartTimer =
          new Timer.periodic(new Duration(seconds: 5), (Timer timer) async {
        sendMessage("===5oiR55qE5b+D6Lez===");
      });

      // 监听事件
      void onData(dynamic content) {
        callBack(content);
      }

      webSocket.listen(onData, onError: (a) {
        closeSocket();
      }, onDone: () {
        closeSocket();
      });
    }).onError((error, stackTrace) {
      closeSocket();
    });
  }

  static void closeSocket() {
    heartTimer?.cancel();
    webSocket?.close();
    isconnect = false;
    webSocket = null;
  }

  static void reConnect(Function callBack, String url) {}

  // 向服务器发送消息
  static bool sendMessage(String message) {
    try {
      webSocket?.add(message);
      return true;
    } on Exception catch (e) {
      print(e.toString());
    }
    return false;
  }
}
